package com.stlm2.dems.service;

import com.stlm2.dems.dao.*;
import com.stlm2.dems.entity.*;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.stlm2.dems.entity.CardsState;
import com.stlm2.util.Convert;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;

import com.stlm2.core.base.BaseDao;
import com.stlm2.core.base.impl.BaseServiceImpl;
import org.springframework.ui.ModelMap;

import org.springframework.util.StringUtils;

import java.math.BigDecimal;

import java.sql.Time;
import java.util.*;

@Service("userCardsService")
@Transactional(rollbackForClassName={"java.lang.Exception"}, propagation = Propagation.REQUIRED)
public class UserCardsService extends BaseServiceImpl<UserCards> {

	@Resource
	private UserCardsDao userCardsDao;
	@Resource
	private  DdmGoodsDao ddmGoodsDao;

	@Resource
	private GoodsRelateCategoryDao goodsRelateCategoryDao;
	@Resource
	private  GoodsCategoryDao goodsCategoryDao;

	@Resource
	private GoodSpecificationDao goodSpecificationDao;
	@Resource
	private ValueAddedServicesDao valueAddedServicesDao;
	@Resource
	private  DdmShoppingCartDao ddmShoppingCartDao;
	@Resource
	private DdmGoodsService ddmGoodsService;
	@Resource
	private GoodsCategoryService goodsCategoryService;

	@Override
	protected BaseDao <UserCards> getDao() {
		return userCardsDao;
	}

	public List<ModelMap> convert(List<UserCards> maps){
		List<ModelMap> list = new ArrayList<ModelMap>();
		if(maps != null && maps.size() > 0){
			for(UserCards map : maps){
				ModelMap map2 = buildModel(map);
				list.add(map2);
			}
		}
		return list;
	}
	public ModelMap buildModel(UserCards userCards) {
		ModelMap model = new ModelMap();
		if (userCards != null) {
			Date date=userCards.getEndUseTime();
			Integer cardsState=userCards.getCardsStateValue();
			if(new Date().getTime()>date.getTime()&&cardsState==0){
				userCards.setCardsState(CardsState.Due);
				updateEntity(userCards);
			}
			model.put("id",userCards.getId());
			model.put("name", userCards.getName());
			model.put("cardsType",userCards.getCardsType().toString());
			model.put("cardsTypeValue",userCards.getCardsTypeValue());
			model.put("money", userCards.getMoney());
			model.put("validDay",userCards.getValidDay());
			model.put("goodsId",userCards.getGoodsId()!=null?userCards.getGoodsId():"");
			model.put("goodsName",userCards.getGoodsId()!=null?ddmGoodsService.findEntityById(userCards.getGoodsId()).getName():"");
			model.put("goodsCategoryId",userCards.getGoodsCategoryId()!=null?userCards.getGoodsCategoryId():"");
			model.put("goodsCategoryName",userCards.getGoodsCategoryId()!=null?goodsCategoryService.findEntityById(userCards.getGoodsCategoryId()).getName()+"类":"");
			model.put("endUseTime", Convert.toShortYMD(date));
			model.put("img","../phoneImg/index_coupon_icon.png");
			model.put("cardsState",userCards.getCardsState().toString());
			model.put("beginTime",Convert.toShortYMD(userCards.getGetTime()));
		}
		return model;
	}

	/*
   * 获取用户手上有效，且可用的卡券集合，与暂时不可用的卡券
   * */
	public Map<String,Object> validAndUserable(int userId, String orderInfo ){

		//ffl 更改过期卡券 状态为 过期状态
		userCardsDao.updateStateToDue(userId);

                  /*
         * 先获取所有有效，且不过期的券
         * */
         Map<String,Object> map =  new HashMap<String, Object>();
		List<UserCards> timeOutList = new ArrayList<UserCards>();
		List<UserCards> useAbleList = new ArrayList<UserCards>(); //存放最终结果的userCards
		List<UserCards> unUserAbleList = new ArrayList<UserCards>();//暂时不能使用的卡券集合
		List<DdmGoods> goodList = new ArrayList<DdmGoods>(); //存放商品信息
		BigDecimal money = new BigDecimal(0);//商品加上增值服务一共需要的金钱包括是否是规格产品都考虑在内
		List<GoodsCategory> listCategory = new ArrayList<GoodsCategory>(); //商品所属的分类
		timeOutList = userCardsDao.timeOutCards(userId);
		List<Integer> useCardIdList = new ArrayList<Integer>();

		BigDecimal addsServicePrice = new BigDecimal(0);
		/*
		* 从数据库中获取有用的卡券
		* */
		List<UserCards> list = userCardsDao.validCards(userId); //获取从数据库中获取的有用的卡券集合

          /*
          * 处理orderInfo
          *
          * */
		if(!StringUtils.isEmpty(orderInfo)){
			JSONArray jsonArray = JSONArray.fromObject(orderInfo);//并将DS内容取出转为json数组

			for (int i = 0; i < jsonArray.size(); i++) {     //遍历json数组内容
				JSONObject object = jsonArray.getJSONObject(i);
				int goodId = object.getInt("goodId");
				int num = object.getInt("num");//如果有规格则是规格商品的个数，否则是无规格商品的个数
				DdmGoods goods  = ddmGoodsDao.getById(goodId);
				if (goods.getState()==false){//如果此商品下架或者无效
					map.put("code",0);
					map.put("msg","商品无效id为"+goods.getId());
					return  map;
				}else {
					goodList.add(goods);  //将商品加入集合
				/*
				* 缔造有效商品所属的有效分类
				* mapper中直接获取的都是有效的
				* */
					List<GoodsRelateCategory> goodsRelateCategoryList =  goodsRelateCategoryDao.getByGoodsId(goodId);
					if(goodsRelateCategoryList!=null&&goodsRelateCategoryList.size()>0){//商品获取到有效的关联对象
						for(GoodsRelateCategory goodsRelateCategory:goodsRelateCategoryList){
							GoodsCategory goodsCategory = goodsCategoryDao.getById(goodsRelateCategory.getGoodsCategoryId());
							if(goodsCategory.getIsValid()){
								listCategory.add(goodsCategory);
							}
						}
					}
				}


				int goodNum = object.getInt("num");
				int gooodSpecificationId = 0;
				String addService = "";
				try{
					gooodSpecificationId= object.getInt("goodSpecificationId");
				}catch (Exception e){
					gooodSpecificationId=0;
				}
				try{
					addService= object.getString("addService");
				}catch (Exception e){
					addService="";
				}
			/*
			* 计算传递过来的商品一共多少钱
			* */
				BigDecimal goodPirce = new BigDecimal(0);
				BigDecimal goodSpecificationPirce = new BigDecimal(0);
				BigDecimal addPrice = new BigDecimal(0);
				String addServieArray[] = addService.split(",");
				if(gooodSpecificationId==0){//表示此商品没有规格
					goodPirce = goods.getMemberPrice();
					goodPirce = goodPirce.multiply(new BigDecimal(num));
				}else{//此商品有规格
					GoodSpecification goodSpecification = goodSpecificationDao.getById(gooodSpecificationId);
					if(goodSpecification!=null){
						goodSpecificationPirce = goodSpecification.getMemberPrice();
						goodSpecificationPirce = goodSpecificationPirce.multiply(new BigDecimal(num));
					}



				}
				if(!StringUtils.isEmpty(addService)){
/*
				计算增值服务的价格
				*/
					for(int k =0;k<addServieArray.length;k++){
						int  addServiceId = Integer.valueOf(addServieArray[k]);
						//获取增值服务对象
						ValueAddedServices valueAddedService = valueAddedServicesDao.getById(addServiceId);
						//判断增值服务对象是否有有效
						if(valueAddedService.getState()==true){
							addPrice.add(valueAddedService.getPrice());
						}
					}
					addsServicePrice.add(addPrice);

				}

				money.add(goodPirce).add(goodSpecificationPirce).add(addsServicePrice);
			}

		}else{
			//数据库中获取而不是前台传递过来进行处理
			List<DdmShoppingCart> cartList =  ddmShoppingCartDao.getByUserId(userId);
			if(cartList==null||cartList.size()==0){//购物车中没有任何有效的商品数据
				map.put("code",0);
				map.put("msg","购物车为空");
				return  map;
			}
		   /*
		   * 遍历购物车中的每一条记录
		   * */
			for(DdmShoppingCart ddmShoppingCart:cartList){

			int goodId =ddmShoppingCart.getGoodsId();
			int goodNum = ddmShoppingCart.getCount();//如果有规格则是规格商品的个数，否则是无规格商品的个数
			DdmGoods goods  = ddmGoodsDao.getById(goodId);
			if (goods.getState()==false){//如果此商品下架或者无效
                ddmShoppingCart.setShoppingCartState(ShoppingCartState.NoSelect);
				continue;
			}else {
				goodList.add(goods);  //将商品加入集合
				/*
				* 缔造有效商品所属的有效分类
				* mapper中直接获取的都是有效的
				* */
				List<GoodsRelateCategory> goodsRelateCategoryList =  goodsRelateCategoryDao.getByGoodsId(goodId);
				if(goodsRelateCategoryList!=null&&goodsRelateCategoryList.size()>0){//商品获取到有效的关联对象


					for(GoodsRelateCategory goodsRelateCategory:goodsRelateCategoryList){
						GoodsCategory goodsCategory = goodsCategoryDao.getById(goodsRelateCategory.getGoodsCategoryId());
						if(goodsCategory.getIsValid()==true){
							listCategory.add(goodsCategory);
						}
					}

				}

			}



			int gooodSpecificationId = 0;
			String addService = "";
			try{
				gooodSpecificationId=ddmShoppingCart.getSpecificationId();
			}catch (Exception e){
				gooodSpecificationId=0;
			}
			try{
				addService= ddmShoppingCart.getValueAddedServicesIds();
				if(addService==null){
					addService="";
				}
			}catch (Exception e){
				addService="";
			}
			/*
			* 计算传递过来的商品一共多少钱
			* */
			BigDecimal goodPirce = new BigDecimal(0);
			BigDecimal goodSpecificationPirce = new BigDecimal(0);
			BigDecimal addPrice = new BigDecimal(0);
			String addServieArray[] = addService.split(",");
			if(gooodSpecificationId==0){//表示此商品没有规格
				goodPirce = goods.getMemberPrice();
				goodPirce = goodPirce.multiply(new BigDecimal(goodNum));
			}else{//此商品有规格
				GoodSpecification goodSpecification = goodSpecificationDao.getById(gooodSpecificationId);
				if(goodSpecification!=null){
					goodSpecificationPirce = goodSpecification.getMemberPrice();
					goodSpecificationPirce = goodSpecificationPirce.multiply(new BigDecimal(goodNum));
				}



			}
				if(!StringUtils.isEmpty(addService)){

					for(int k =0;k<addServieArray.length;k++){
						int  addServiceId = Integer.valueOf(addServieArray[k]);
						//获取增值服务对象
						ValueAddedServices valueAddedService = valueAddedServicesDao.getById(addServiceId);
						//判断增值服务对象是否有有效
						if(valueAddedService.getState()==true){
							addPrice.add(valueAddedService.getPrice());
						}
					}
					addsServicePrice.add(addPrice);
				}

			money.add(goodPirce).add(goodSpecificationPirce).add(addsServicePrice);
			}

		}


        /*
        * 遍历所有的卡券，并且保留最终有用的结果
        * */
		for(UserCards userCards:list){

			 if(CardsType.Good.equals(userCards.getCardsType())){ //如果此卡券是商品券
               /*
               * 判断此卡券是否是有效商品中的某个卡券
               * */
				 for(DdmGoods goods: goodList){
					  if(goods.getId()==userCards.getGoodsId()){//此卡券正好是某个商品的卡券
                           useAbleList.add(userCards);
						  useCardIdList.add(userCards.getId());
						  break;
					  }

				 }
			}else if(CardsType.Category.equals(userCards.getCardsType())){//判断此卡券是否是某个分类可用
                          for(GoodsCategory goodsCategory:listCategory){
							        if(goodsCategory.getId()==userCards.getGoodsCategoryId()){
                                         useAbleList.add(userCards);
										useCardIdList.add(userCards.getId());
										break;
									}

						  }

			}else{//不可使用卡券
               unUserAbleList.add(userCards);
			}


		}
		 /*
		 * 将过期的卡券也放入到无用的卡券列表中
		 * */

             map.put("useAbleList",useAbleList);
		     map.put("unUseAbeList",unUserAbleList);
		    map.put("timeOutList",timeOutList);
		     map.put("useAbleNum",useAbleList.size());
		      map.put("unUseAbleNum",unUserAbleList.size()+timeOutList.size());
             map.put("useCardsIdList",useCardIdList);
		map.put("code",1);
		return map;

	}
   /*
   *
   * 获取用户的有效卡券，并进行是否是此用户的判断和处理
   * */
	public Map<String,Object> getValidCards(String userCardsId,Integer userId){
		Map<String,Object> map = new HashMap<String, Object>();
		List<UserCards> userCardsList = new ArrayList<UserCards>();
        String[] args  = userCardsId.split(",");


       for(int i=0;i<args.length;i++){
         UserCards userCards = userCardsDao.getById(Integer.valueOf(args[i]));
		    if(userCards==null){
              map.put("code",0);
				map.put("msg","id为"+args[i]+"的usercards不存在");
				 return  map;
			}else if(userCards.getUserId()-userId!=0){
                    map.put("code","0");
                    map.put("msg","usercardsid为"+args[i]+"的券不属于用户id:"+userId);
                    return  map;
			}else if(CardsState.Unused.equals(userCards.getCardsState())){//此券并未使用
                //判断是否已经过期
                 Date endTime = userCards.getEndUseTime();
				  Date nowTime = new Date();
				if(nowTime.getTime()>endTime.getTime()){
                    //表示此卡券已经过期
                       userCards.setCardsState(CardsState.Due);
					userCardsDao.modify(userCards);
				}else {
					//此卡券不仅状态正确，时间上也是没有过期的卡券
                     userCardsList.add(userCards);
				}

			}

	   }
		Set<Integer> set = new HashSet<Integer>();
		for(UserCards userCards:userCardsList){
			 set.add(userCards.getCardsId());

		}
		if(set.size()!=userCardsList.size()){
          map.put("code",0);
          map.put("msg","一个用户不能拥有同一个卡券多个");
             return  map;
		}
		map.put("code",1);
		map.put("userCardList",userCardsList);
		return  map;
	}




	//ffl 简化数据
	public List<ModelMap> convert_simplify(List<UserCards> userCardsList){
		List<ModelMap> list = new ArrayList<ModelMap>();
		if(userCardsList!= null &&userCardsList.size() > 0){
			for(UserCards userCards : userCardsList){
				ModelMap map = buildModel_simplify(userCards);
				list.add(map);
			}
		}

		return list;
	}

	public ModelMap buildModel_simplify(UserCards userCards){
		ModelMap model = new ModelMap();
		if(userCards != null){
			model.put("id",userCards.getId());
			model.put("name", userCards.getName());
			model.put("cardsType",userCards.getCardsType().toString());
			model.put("cardsTypeValue",userCards.getCardsTypeValue());
			model.put("money", userCards.getMoney());
			model.put("endUseTime", Convert.toShortYMD(userCards.getEndUseTime()));
			model.put("cardsState",userCards.getCardsState().toString());
			model.put("beginTime",Convert.toShortYMD(userCards.getGetTime()));
		}
		return model;
	}
   /*
   * sfy
   * 2017年11月4日15:44:26
   * 通过商品的id和在可用卡券中查找属于此商品可用的卡券
   *
   * */
	public UserCards goodCanUseUserCard(Integer goodId,List<UserCards> list){
		if(list.size()==0||list==null){
              return  null;
		}

       for(UserCards userCards:list){
		   if(CardsType.Good.equals(userCards.getCardsType())){//表示此券是商品券
                //判断此商品是不是有可用的商品券
			     if(userCards.getGoodsId()==goodId){
                    return  userCards;

				 }

		   }else if(CardsType.Category.equals(userCards.getCardsType())){//表示此券是分类券
			   List<GoodsRelateCategory> goodsRelateCategoryList =  goodsRelateCategoryDao.getByGoodsId(goodId);
            for(GoodsRelateCategory goodsRelateCategory: goodsRelateCategoryList){
                  if(goodsRelateCategory.getGoodsCategoryId()==userCards.getGoodsCategoryId()){
                       return userCards;
				  }
			}
		   }

	   }
		return  null;
	}


	/*
	* sfy
	* 2017年11月7日09:43:30
	* 将list中的一个对象去掉
	* */
	 public  List<UserCards> removeUserCards(UserCards userCards,List<UserCards> list){
		   List<UserCards> resultList = new ArrayList<UserCards>();
		         for(UserCards userCards1:list){
					  if(userCards.getId()!=userCards1.getId()){
						   resultList.add(userCards1);
					  }

				 }

            return  resultList;
	 }

	public UserCards findEntityByUserCards(UserCards userCards) {
	 	return userCardsDao.findEntityByUserCards(userCards);
	}
}